package sicnu.cs.ich.security.security.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import sicnu.cs.ich.api.common.enums.ResultEnum;
import sicnu.cs.ich.common.util.ResultInfoUtil;
import sicnu.cs.ich.security.exceptions.exception.EmailLoginException;
import sicnu.cs.ich.security.exceptions.exception.WechatLoginException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        String message = null;
        if (ex instanceof LockedException) {
            message = "账号被锁定，请联系管理员";
        }else if(ex instanceof UsernameNotFoundException || ex instanceof BadCredentialsException){
            message = "用户名或密码错误";
        }else if (ex instanceof EmailLoginException|| ex instanceof WechatLoginException){
            message = ex.getMessage();
        } else{
            message = "登录异常："+ex.getMessage();
        }
        // BadCredentialsException
        response.getWriter().println(objectMapper.writeValueAsString(ResultInfoUtil.buildError(ResultEnum.ERROR, message)));
        response.getWriter().close();
    }
}
